package com.candy.candyproduct.config.weightBalance;

import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/8/17 9:56
 * @Description 描述
 */
public class WeightedBalancer extends Balancer {

    public static Instance chooseInstanceByRandomWeight(List<Instance> instanceList, String clusterName) {
        // 这是父类Balancer自带的根据随机权重获取服务的方法.
        List<Instance> collect = null;
        if (StringUtils.isNotBlank(clusterName) && !CollectionUtils.isEmpty(instanceList)) {
            collect = instanceList.stream().filter(i -> clusterName.equals(i.getClusterName())).collect(Collectors.toList());
        }
        return getHostByRandomWeight(CollectionUtils.isEmpty(collect) ? instanceList : collect);
    }

}
